package com.ss.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtils {

    //有效期
    public static final Long JWT_TTL = 60 * 60 * 1000L;//一小时

    //秘钥明文
    public  static final String JW_KEY = "sangeng";

    public static String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 生成jwt
     * @param subject subject token中要存放的数据（json格式）
     */
    public static String createJWT(String subject){
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());//设置过期时间
        return builder.compact();
    }

    /**
     *
     * @param subject
     * @param ttlMillis
     * @param uuid
     * @return
     */
    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis = JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder().setId(uuid)//唯一uuid
                .setSubject(subject)//主题，可以是json数据
                .setIssuer("sg")//签发者
                .setIssuedAt(now)//签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名，第二个参数是秘钥
                .setExpiration(expDate);
    }

    /**
     * 生成jwt
     * @param subject subject token中要存放的数据（json格式）
     */
    public static String createJWT(String id, String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);//设置过期时间
        return builder.compact();
    }

    /**
     * 生成jwt
     * @param subject subject token中要存放的数据（json格式）
     */
    public static String createJWT(String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());//设置过期时间
        return builder.compact();
    }

    public static SecretKey generalKey(){
        byte[] encodeKey = Base64.getDecoder().decode(JW_KEY);
        SecretKey key = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
        return key;
    }

    public static Claims parserJWT(String jwt) throws Exception{
        SecretKey secretKey = generalKey();
        return  Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) throws Exception {
        String jwt = createJWT("{\"name\":\"java\",\"id\":1}");
        System.out.println(jwt);
        Claims claims = parserJWT(jwt);
        System.out.println(claims.getSubject());
    }
}
